import React, { useEffect, useMemo, useState } from "react";
import axios from "axios";
import "./style.css";

interface CityState {
  name: string;
  children: {
    name: string;
  }[];
}

const Index: React.FC = () => {
  const [city, setCity] = useState<CityState[]>([]);
  const [activeIndex, setActiveIndex] = useState(-1);
  const childrenCity = useMemo(() => {
    if (activeIndex === -1) return [];
    return city.length ? city[activeIndex].children : [];
  }, [city, activeIndex]);

  useEffect(() => {
    (async () => {
      const resp = await axios.get("/api/city");
      setCity(resp.data.data);
    })();
  }, []);

  return (
    <div className="city">
      <div className="left">
        {city.map((v, i) => {
          return (
            <span
              key={i}
              className={i === activeIndex ? "active" : ""}
              onClick={() => setActiveIndex(i)}
            >
              {v.name}
            </span>
          );
        })}
      </div>
      <div className="right">
        {childrenCity.map((v, i) => {
          return (
            <div className="item" key={i}>
              <span>{v.name}</span>
              <span>&gt;</span>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default Index;
